Macromedia Flex Article

Providing a Flex Front End to Your Struts Applications

Christophe Coenraets

www.macromedia.com

Struts is an open source framework that facilitates the development of web applications based on Java servlets and other related technologies. Because it provides a solution to many of the common problems developers face when building these applications, Struts has been widely adopted in a large variety of development efforts, from small projects to large-scale enterprise applications.

Although Struts greatly facilitates the task of developers, it doesn't do much to improve the end-user experience: the end-result is still an application delivered in HTML and using the traditional HTTP request/response mechanism.

Developers—and organizations in general—are increasingly looking for solutions to provide their applications with a more engaging user experience that overcomes the limitations of HTML.

Macromedia Flex is a presentation server that addresses this requirement and allows developers to build a new generation of Rich Internet Applications (RIAs) that combine the usability of desktop applications with the reach of traditional web applications.

This article describes how you can provide your Struts applications with a rich front end using Flex technology. The objective of this article is not to make a case for Rich Internet Applications. It assumes that you already understand their value. This article focuses on the Flex/Struts integration from an architectural and technical point of view.

To run the code in this article, you may want to join the Flex Beta. Flex runs on top of a J2EE Application Server such as Macromedia JRun, IBM Websphere, BEA WebLogic, or Apache Tomcat. In the future, Flex will also run on top of Microsoft .NET server. You can try or buy Macromedia JRun below:

Macromedia JRun


Improving the View in Your MVC Architecture

Struts and Flex are both based on a Model-View-Controller (MVC) architecture.

  • Struts primarily focuses on the controller part of the MVC architecture. In addition, it provides JSP tag libraries to help you create the view in a traditional JSP/HTML environment.
  • Flex primarily focuses on the view part of the MVC architecture. It also provides some controller logic to help communicate with remote systems and implement security.

The promise of the Model-View-Controller architecture is that by creating components with a well-defined and limited scope in your application, you increase the reusability of these components and improve the maintainability of the overall system. In addition, you should also be able to swap components in one partition without affecting the entire system. The Flex/Struts integration builds on that promise. In many ways, using Flex in your Struts application simply consists of providing your application with an alternate, richer, and smarter view.

You can either entirely replace your existing views with a Flex-based user interface, or let the two view systems coexist in the same application, and even in the same page. For example, you can still provide browsing aspects of your site with HTML, while the Flex application provides the more interactive sections of the site.

Although you can consider the Flex application part of the View in a distributed MVC (Model 2 MVC), it also implements its own classic MVC architecture at the client side. A Flex application has its own view components (typically written in MXML), model components (representing data at the client side), and controller components (responsible for the communication with back-end systems, for example). This client-side separation of task is not available in HTML. Rich Internet Applications eliminate the need to rely heavily on complex Model 2 variations of MVC.

The Struts Framework

Struts primarily focuses on the Controller part of the MVC architecture and integrates with other technologies to provide the model and the view. For the model, Struts interacts with standard data access technologies, such as JDBC and EJB. For the view, Struts provides a set of tag libraries to help you create JavaServer Pages. Struts also works with other presentation technologies such as Velocity, XSLT, and, as this article describes, the Flex presentation server.

The following table describes the key components of the Struts framework.

ActionServlet ActionServlet is Struts' front controller servlet. In a Struts application, all HTTP requests route through the ActionServlet.
ActionMapping

ActionMapping objects are created from the struts-config.xml file. An ActionMapping object describes how to handle a specific request. It specifies:

  • The request path. The ActionServlet matches the incoming request path against this property to select the appropriate ActionMapping.
  • The ActionForm object to use.
  • The Action object to use.
  • A list of possible forward destinations. The Action object selects the actual forward destination.
ActionForm An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. An ActionForm object is automatically populated on the server side with data entered from a form on the client side.
Action An Action is defined by a class that extends org.apache.struts.action.Action. An Action object controls the action to perform for a specific request. The Action object typically interacts with Model objects (JavaBeans or EJBs) to execute some business logic. Based on the success or failure of the operation, the Action object uses an ActionForward object to tell the ActionServlet where to forward the request next.
ActionForward Specifies a resource where the Action object should forward the request after handling it.

Struts Workflow

The following diagram represents the workflow of a traditional Struts application:

The workflow of a traditional Struts application

Figure 1. The workflow of a traditional Struts application.

  1. The ActionServlet receives the request.
  2. Based on the request URI, the ActionServlet retrieves the ActionMapping that defines the request.
  3. The ActionServlet populates the ActionForm object from the HTTP request. If the ActionMapping specifies that validation is required, the ActionServlet calls the validate() method on the ActionForm object.
  4. The ActionServlet invokes the execute() method of the Action object, providing the ActionForm object as a parameter. The method returns an ActionForward object specifying where to forward the request.
  5. The ActionServlet forwards the request to the resource specified in the ActionForward object. This is typically a JSP (the view), but it can send the request to another Action.
  6. It sends the response back to the browser.

A Sample Struts Application

This article uses a simple application to demonstrate how you can use Flex with Struts. The sample application is a registration module that customers use to register with our fictive website.

The action is defined as follows in struts-config.xml:

<action
    path="/RegistrationSubmit"
    type="samples.struts.RegistrationAction"
    name="registrationForm"
    scope="request"
    validate="true"
    input="/registration/registration.jsp">
    <forward name="success" path="/registration/confirm.jsp"/>
</action>

The following diagram illustrates the workflow of the Registration application:

The workflow of the Registration application

Figure 2. The workflow of the Registration application.

The RegisterAction class is defined as follows:

package samples.struts;

import javax.servlet.http.*;
import org.apache.struts.action.*;

public final class RegistrationAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form, 
			HttpServletRequest request, HttpServletResponse response) throws Exception {

        ActionErrors errors = new ActionErrors();
        RegistrationForm registrationForm = (RegistrationForm) form;
        String email = registrationForm.getEmail();

        // Dummy business logic: here is where you would typically communicate with a business object
        if (email == null || email.indexOf("@") < 0) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.registration.failed"));
            saveErrors(request,errors);
            return new ActionForward(mapping.getInput());
        }

        request.setAttribute("registration", form);
        return mapping.findForward("success");
    }

 }

Note: In this example, the Action implements dummy business logic: a simple e-mail address verification. In a real life scenario, the Action would probably delegate a database insertion to a business object.

The confirm.jsp page is defined as follows:

<%@ page import="java.util.Enumeration"%>
<%@ taglib uri="/tags/struts-bean" prefix="bean" %>
Thank you for registering:<br>
<bean:write name="registration" property="firstName"/><br>
<bean:write name="registration" property="lastName"/><br>
<bean:write name="registration" property="phone"/><br>
<bean:write name="registration" property="email"/>

Providing a Struts Application with a Flex Front End

With Flex, you can provide a rich front end to your Struts applications. The remainder of this article discusses two different approaches to implement this integration. The two approaches correspond to the two different ways a Flex application communicates with remote systems:

  • Using the traditional HTTP request/response mechanism
  • Using SOAP to invoke methods on remote services

Approach 1: Traditional HTTP Request/Response Integration

In this approach, you use the Flex HTTPService to communicate with Struts using the traditional HTTP request/response mechanism. In other words, you keep using Struts exactly the way you use it with a traditional HTML-based view system. This approach has no impact on the model and the controller aspects of your Struts application.

To implement the Registration application using this approach, the only change you have to make is to modify confirm.jsp to dynamically generate an XML response instead of an HTML response. When the Flex application receives the XML response, it can adjust the user interface accordingly.

The following diagram illustrates the workflow of the Registration application implemented using this approach.

Workflow of the Registration application with the HTTP request/response approach

Figure 3. Workflow of the Registration application with the HTTP request/response approach

The Flex client application is implemented as follows:

<?xml version="1.0" encoding="iso-8859-1"?>

<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" height="600">

    <mx:HTTPService id="registrationRequest" url="/royale/RegistrationSubmitFlex.do"
        result="alert(registrationRequest.result.registration.status)">
        <mx:request>
            <firstName>{firstName.text}</firstName>
            <lastName>{lastName.text}</lastName>
            <phone>{phone.text}</phone>
            <email>{email.text}</email>
        </mx:request>
    </mx:HTTPService>

    <mx:Form>
        <mx:FormItem label="First Name" required="true">
            <mx:TextInput id="firstName" width="200"/>
        </mx:FormItem>
        <mx:FormItem label="Last Name" required="true">
            <mx:TextInput id="lastName" width="200"/>
        </mx:FormItem>
        <mx:FormItem label="Phone" required="true">
            <mx:TextInput id="phone" width="200"/>
        </mx:FormItem>
        <mx:FormItem label="Email" required="true">
            <mx:TextInput id="email" width="200"/>
        </mx:FormItem>
        <mx:FormItem>
            <mx:Button label="Register" click="registrationRequest.send()"/>
        </mx:FormItem>
    </mx:Form>

    <mx:Repeater id="errorList" dataProvider="{registrationRequest.result.registration.error}">
        <mx:Label>{errorList.currentItem}</mx:Label>
    </mx:Repeater>

</mx:Application>

Code Highlights:

  • You use the Flex data binding mechanism to bind the page parameters of the HTTP request to the data input controls: when the user makes changes in user interface controls, the request parameters are changed accordingly.
  • The errorList Repeater is bound to the result of the registrationRequest HTTPService: When registrationRequest receives the XML response, the Repeater automatically displays a label corresponding to each <error> tag in the response.
  • You can also use the result event handler of the HTTPService tag to do something relevant to your application when it receives the response. This example displays a message box indicating the success or the failure of the registration.

As mentioned earlier, the confirm.jsp page now generates an XML document instead of an HTML document:

<registration>
<%
    Object errors = request.getAttribute("org.apache.struts.action.ERROR");
    if (errors==null) {
%>
        <status><bean:message key="status.success"/></status>
<%
    } else {
%>
        <status><bean:message key="status.failure"/></status>
<%
    }
%>
</registration>

Note: Notice that the application uses the Struts tags to generate the XML response. Among other advantages, this means that you can still fully leverage the internationalization features built into Struts.

Alternative Implementation: Supporting Flex and HTML in Parallel

Rather than modifying confirm.jsp to generate XML instead of HTML, you can also create a new action mapping in struts-config.xml. The new action mapping uses the same ActionForm and Action objects, but forwards the request to another JSP (confirmxml.jsp). This approach allows you to simultaneously support HTML and Flex clients.

<action
    path="/RegistrationSubmit"
	type="samples.struts.RegistrationAction"
	name="registrationForm"
	scope="request"
	validate="true"
	input="/registration/registration.jsp">
	<forward name="success" path="/registration/confirm.jsp"/>
</action>

<action
	path="/RegistrationSubmitFlex"
	type="samples.struts.RegistrationAction"
	name="registrationForm"
	scope="request"
	validate="true"
	input="/registration/confirmxml.jsp">
	<forward name="success" path="/registration/confirmxml.jsp"/>
</action>

Approach 2: SOAP Integration

The traditional HTTP request/response integration approach works well because it fits perfectly in Struts' workflow and, at the same time, provides the end-user with all the benefits of Rich Internet Applications.

So why a second integration approach? The fact is that with the advent of new technologies such as Rich Internet Applications and SOAP, some of the problems that the Struts framework solved in a traditional HTML / HTTP environment have disappeared. For example, Rich Internet Applications allow you to maintain state information at the client side, and SOAP allows you to invoke methods on remote objects using the HTTP protocol.

The integration approach in this section does the following:

  • Fully leverages the capabilities of Rich Internet Applications and SOAP.
  • Bypasses Struts features that you no longer need when you use these technologies.
  • Allows your client application to interact directly with the relevant Struts components exposed as services.

Using a Service Façade

Because, in the Struts framework, controller components rely heavily on the HTTP request/response mechanism, the Request and Response objects are omnipresent in their API. To present an API that doesn't have these dependencies, you can add a service façade in front of the Struts objects you want to expose. The service façade is a frequently used pattern in a Service-Oriented Architecture (SOA). It makes your existing Struts model available to other service clients outside of Flex.

The following diagram illustrates the workflow of the Registration application implemented using this approach (RegistrationService is the service façade). Notice that the client now communicates with the server on a component-to-service basis instead of on a page-to-front-controller basis.

The workflow of the Registration application using the SOAP approach

Figure 4. The workflow of the Registration application using the SOAP approach.

Note: Struts is a flexible framework that developers use in many different ways. The specifics of the solution presented in this section might therefore not be directly applicable to your application, but the overall approach is. The point of this approach is that your client application can now connect directly to the relevant parts of your Struts applications, whatever these relevant parts are in the context of your application.

The RegistrationService class is defined as follows:

package samples.struts;

import org.apache.struts.action.*;
import java.util.*;

public class RegistrationService {

    public ArrayList register(RegistrationForm form) {

        // Validate form fields
        ActionErrors errors = form.validate(null, null);

        // Execute Action only if form validation succeeded
        if (errors.isEmpty()) {
            RegistrationAction action=new RegistrationAction();
            errors = action.execute(form);
        }

        // Build an array of error messages to be returned to client application
        ArrayList messages = new ArrayList();

        Iterator i = errors.get();
        while (i.hasNext()) {
            messages.add(((ActionError) i.next()).getKey());
        }

        return messages;

    }
}

Code Highlights

Notice that the register() method takes a RegistrationForm object as a parameter: In this case, you use the Struts-based RegistrationForm JavaBean as a value object to transfer the registration data from the client to the server. The workflow of this interaction is as follows:

  1. The Flex application has an ActionScript version of that object. The application populates an instance of that object.
  2. The ActionScript object is serialized into the SOAP request at the client side.
  3. The object is deserialized into an instance of the RegistrationForm JavaBean at the server side.

You also refactor the RegistrationAction class to support both request/response and SOAP invocations without duplicating code.

package samples.struts;

import javax.servlet.http.*;
import org.apache.struts.action.*;

public final class RegistrationAction extends Action {

    public ActionForward execute(ActionMapping mapping, ActionForm form, 
HttpServletRequest request, HttpServletResponse response) throws Exception {

        ActionErrors errors = execute(form);

        if (!errors.isEmpty()) {
            saveErrors(request,errors);
            return new ActionForward(mapping.getInput());
        }

        request.setAttribute("registration", form);
        return mapping.findForward("success");
    }
 
    public ActionErrors execute(ActionForm form) {

        ActionErrors errors = new ActionErrors();

        RegistrationForm registrationForm = (RegistrationForm) form;
        String email = registrationForm.getEmail();

        // Dummy business logic: here is where you would typically communicate with a business object
        if (email == null || email.indexOf("@") < 0) {
            errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.registration.failed"));
        }

        return errors;
    }

}

There are two strategies for exposing Struts components (or their façade) as services:

  • You can expose the components as web services.
  • You can use Flex's RemoteObject to invoke methods directly on Struts components (or their Façade). Notice that behind the scenes RemoteObject also handles your remote method invocation using SOAP.

The strategy you choose is really an implementation detail. Using web services is a more general approach and gives you more flexibility. For example, the Flex application doesn't have to be on the same machine as the Struts application. Using RemoteObject might be a simpler approach if your Flex and your Struts applications live on the same machine and you don't want to go through the extra effort of exposing components as web services.

The source code below is the web services strategy. The Flex client application interoperates with the RegistrationService exposed as a web service.

<?xml version="1.0" encoding="iso-8859-1"?>

<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" height="600">

    <mx:WebService id="registrationWS" wsdl="http://localhost:8101/royale/services/Registration?wsdl"
        result="alert(registrationWS.register.result==null?'Thank You!':'Sorry, your registration failed')">
        <mx:operation name="register">
            <mx:request>
                <form>{registrationModel}</form>
            </mx:request>
        </mx:operation>
    </mx:WebService>

    <mx:Model id="registrationModel">
        <firstName>{firstName.text}</firstName>
        <lastName>{lastName.text}</lastName>
        <phone>{phone.text}</phone>
        <email>{email.text}</email>
    </mx:Model>

    <mx:Form>
        <mx:FormItem label="First Name" required="true">
            <mx:TextInput id="firstName" width="200"/>
        </mx:FormItem>
        <mx:FormItem label="Last Name" required="true">
            <mx:TextInput id="lastName" width="200"/>
        </mx:FormItem>
        <mx:FormItem label="Phone" required="true">
            <mx:TextInput id="phone" width="200"/>
        </mx:FormItem>
        <mx:FormItem label="Email" required="true">
            <mx:TextInput id="email" width="200"/>
        </mx:FormItem>
        <mx:FormItem>
            <mx:Button label="Register" click="registrationWS.register.send()"/>
        </mx:FormItem>
    </mx:Form>

    <mx:Repeater id="errorList" dataProvider="{registrationWS.register.result.item}">
        <mx:Label>{errorList.currentItem}</mx:Label>
    </mx:Repeater>

</mx:Application>

Code Highlights

  • The <mx:Model> tag represents the data.
  • Data elements in the <mx:Model> tag are bound to the data input controls: When the user makes changes in user interface controls, the <mx:Model> tag automatically reflects the changes.
  • The input parameter of the web service's register method is bound to the registrationModel: When you invoke the method, it passes the registrationModel automatically as an argument.

Behind the scenes, registrationModel is represented by an ActionScript object. The properties of this object match the properties of the server-side RegistrationForm JavaBean. You can therefore use registrationModel as the input parameter for the register() method in the RegistrationService class exposed as a web service: Flex serializes registrationModel into a SOAP request on the client side and deserializes the SOAP packet into an instance of the RegistrationForm JavaBean at the server side.

Alternative Implementation

Instead of using the <mx:Model> tag to represent the data, you can also use your own ActionScript object. For example, you could create a RegistrationForm.as class as follows:

class RegistrationForm {

    var firstName:String;
    var lastName:String;
    var phone:String;
    var email:String;

    function RegistrationForm(firstName:String, lastName:String, phone:String, email:String) {
        this.firstName=firstName;
        this.lastName=lastName;
        this.phone=phone;
        this.email=email;
    }

}

You can then use this class instead of the <mx:Model> tag to represent the registration data on the client side:

<?xml version="1.0" encoding="iso-8859-1"?>

<mx:Application xmlns:mx="http://www.macromedia.com/2003/mxml" height="600">

    <mx:Script>

        var form;

        function register() {
            form = new RegistrationForm(firstName.text, lastName.text, phone.text, email.text);
            registrationWS.register.send();
        }

    </mx:Script>

    <mx:WebService id="registrationWS" wsdl="http://localhost:8101/royale/services/Registration?wsdl"
        result="alert(registrationWS.register.result==null?'Thank You!':'Sorry, your registration failed')">
        <mx:operation name="register">
            <mx:request>
                <form>{form}</form>
            </mx:request>
        </mx:operation>
    </mx:WebService>

    <mx:Form>
        <mx:FormItem label="First Name" required="true">
            <mx:TextInput id="firstName" width="200"/>
        </mx:FormItem>
        <mx:FormItem label="Last Name" required="true">
            <mx:TextInput id="lastName" width="200"/>
        </mx:FormItem>
        <mx:FormItem label="Phone" required="true">
            <mx:TextInput id="phone" width="200"/>
        </mx:FormItem>
        <mx:FormItem label="Email" required="true">
            <mx:TextInput id="email" width="200"/>
        </mx:FormItem>
        <mx:FormItem>
            <mx:Button label="Register" click="register()"/>
        </mx:FormItem>
    </mx:Form>

    <mx:Repeater id="errorList" dataProvider="{registrationWS.register.result.item}">
        <mx:Label>{errorList.currentItem}</mx:Label>
    </mx:Repeater>

</mx:Application>

Conclusion

Although Struts greatly facilitates the task of developers building web applications based on Java, it doesn't attempt to improve the end-user experience. Macromedia Flex addresses this requirement by providing a platform for building Rich Internet Applications. Because Flex and Struts are both based on a Model-View-Controller architecture but focus on different aspects of this architecture, the integration of these two technologies makes a lot of sense. You can implement the Flex/Struts integration using the HTTP request/response mechanism maintaining Struts' traditional workflow, or using a service-oriented architecture (SOA), transforming Struts artifacts into services.


About the author

Christophe Coenraets worked at Powersoft—which then became part of Sybase—from 1994 to 2000. He started working with Java in 1996 and became the Technical Evangelist for the company's Java and Internet Application Division. Christophe then joined Macromedia as the Technical Evangelist for JRun, the company's J2EE application server. In this position, Christophe started working on Rich Internet Applications and on ways of integrating Flash front ends with J2EE back-ends. Christophe is currently the S enior Evangelist for Macromedia's new developer-centric Rich Internet Applications initiative. Christophe has been a regular speaker at conferences worldwide for the last 10 years.